package com.liaowei.article.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liaowei.article.mapper.ArticleUserMapper;
import com.liaowei.article.openfeign.ArticleCommentClient;
import com.liaowei.article.openfeign.UserClient;
import com.liaowei.article.service.ArticleService;
import com.liaowei.article.service.ArticleUserService;
import com.liaowei.common.Constants;
import com.liaowei.common.ErrorCode;
import com.liaowei.exception.CustomerException;
import com.liaowei.model.domain.Article;
import com.liaowei.model.domain.ArticleUser;
import com.liaowei.model.param.ArticleCommentStatusParam;
import com.liaowei.model.param.ArticleHistoryParam;
import com.liaowei.model.param.ArticleUserParam;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
* @author LindaMan
* @description 针对表【wy_article_user(文章-用户表)】的数据库操作Service实现
* @createDate 2023-05-06 23:31:37
*/
@Service
@RequiredArgsConstructor
public class ArticleUserServiceImpl extends ServiceImpl<ArticleUserMapper, ArticleUser>
    implements ArticleUserService {

    private final ArticleUserMapper articleUserMapper;
    private final UserClient userClient;
    private final ArticleService articleService;
    private ArticleCommentClient articleCommentClient;


    /**
     * 点赞文章
     * @param param 点赞参数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String starOrCollArticle(ArticleUserParam param) {
        // 查询文章是否存在
        Article entity = articleService.getById(param.getArticleId());
        if (BeanUtil.isEmpty(entity))
            throw new CustomerException(Constants.PARAM_ERROR, "文章不存在");

        // 查询文章用户记录
        ArticleUser articleUser = articleUserMapper.selectOne(Wrappers.lambdaQuery(ArticleUser.class).eq(ArticleUser::getArticleId, param.getArticleId())
                .eq(ArticleUser::getUserId, param.getUserId()));
        if (BeanUtil.isEmpty(articleUser)) {
            articleUser = new ArticleUser();
            articleUser.setArticleId(param.getArticleId());
            articleUser.setUserId(param.getUserId());
        }

        // 修改文章点赞状态
        articleUser.setStarStatus(param.getStarStatus());
        articleUser.setCollectStatus(param.getCollectStatus());

        // 保存
        try {
            this.saveOrUpdate(articleUser);
        } catch (Exception e) {
            throw new CustomerException(Constants.SYSTEM_ERROR, "操作失败，请稍后重试");
        }

        return "操作成功";
    }

    // 校验用户是否认证
    public void matchUser(Long userId,Long loginId){
        if (!loginId.equals(userId)){
            throw new CustomerException(Constants.PARAM_ERROR,"请先认证");
        }
    }

    /**
     * 根据id修改评论状态
     * @param commentStatusParam 评论状态参数
     * @return 提示信息
     */
    @Override
    public String updateCommentStatus(ArticleCommentStatusParam commentStatusParam) {
        // 查询用户是否已经评论过
        int commentStatus = articleUserMapper.selectCommentStatus(commentStatusParam);
        if (commentStatus == 1){
            throw new CustomerException(Constants.PARAM_ERROR,"已经评论过");
        }
        try {
            articleUserMapper.updateCommentStatus(commentStatusParam);
        } catch (Exception e) {
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);
        }

        return "修改成功";
    }

    /**
     * 保存articleUser
     * @param articleUserParam 保存articleUser参数
     * @return 提示信息
     */
    @Override
    public String saveArticleUser(ArticleUserParam articleUserParam) {
        // 获取文章id
        Long articleId = articleUserParam.getArticleId();
        // 获取当前用户id
        Long userId = articleUserParam.getUserId();
        // 获取当前认证的id
        Long loginId =  Long.parseLong(StpUtil.getLoginId().toString());

        // 判断操作是否是自己操作的
        matchUser(userId,loginId);

        // 构造查询构造器
        LambdaQueryWrapper<ArticleUser> wrapper = Wrappers.lambdaQuery(ArticleUser.class)
                .eq(ArticleUser::getArticleId, articleId)
                .eq(ArticleUser::getUserId, userId);
        ArticleUser articleUser = articleUserMapper.selectOne(wrapper);

        // 获取参数
        Integer collectStatus = articleUserParam.getCollectStatus();
        Integer starStatus = articleUserParam.getStarStatus();
        // 查询是否评论
        int commentStatus = 0;
//        BaseResponse<List<ArticleComment>> response = articleCommentClient.isCommented(articleId, userId);
//        if (response.getCode() == 1 && response.getData().size() > 0){
//            // 设置评论状态
//            commentStatus = response.getData().size();
//        }

        try {
            if (BeanUtil.isEmpty(articleUser)){
                articleUser = new ArticleUser();
                // 新增
                articleUser.setArticleId(articleId);
                articleUser.setUserId(userId);
                articleUser.setAccessNumber(1);
                articleUser.setCollectStatus(collectStatus);
                articleUser.setStarStatus(starStatus);
                articleUser.setCommentStatus(commentStatus);
                articleUserMapper.insert(articleUser);
            }else {
                // 修改
                articleUser.setAccessNumber(articleUser.getAccessNumber() + 1); // 访问量 +1
                articleUser.setCollectStatus(collectStatus);
                articleUser.setCommentStatus(commentStatus);
                articleUser.setUpdateTime(new Date());
                articleUserMapper.updateById(articleUser);
            }

            // 新增浏览历史记录
            ArticleHistoryParam historyParam = new ArticleHistoryParam();
            historyParam.setUserId(userId);
            historyParam.setArticleId(articleId);
            userClient.addArticleHistory(historyParam);


        } catch (Exception e) {
            throw new CustomerException(ErrorCode.SYSTEM_ERROR);
        }

        return "保存成功";
    }
}




